package com.leef.glidetest.glide;

import android.text.TextUtils;

import com.bumptech.glide.Priority;
import com.bumptech.glide.load.data.DataFetcher;
import com.leef.glidetest.bean.SecretData;
import com.leef.glidetest.utils.DecBufferedInputStream;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import cn.finalteam.toolsfinal.io.FileUtils;

/**
 * Created by IWALL on 2016/3/18.
 * data fetcher
 */
public class SecretDataFetcher implements DataFetcher<InputStream> {

    private volatile boolean canceled;
    private final SecretData data;
    private InputStream is;

    public SecretDataFetcher(SecretData data) {
        this.data = data;
    }

    @Override
    public InputStream loadData(Priority priority) throws Exception {
        String path = data.getPath();
        if (path == null) {
            if (canceled) {
                return null;
            }
            path = getLocalPath();
            if (path == null) {
                return null;
            }
            System.out.println("ENC PIC --> " + path);
            data.setPath(path);
        }
        if (canceled) {
            return null;
        }
        is = fetchStream(path);
        return is;
    }

    private InputStream fetchStream(String path) {
        File file = new File(path);
        if (file.exists()) {
            DecBufferedInputStream stream = null;
            try {
                stream = new DecBufferedInputStream(
                        FileUtils.openInputStream(file),
                        DecBufferedInputStream.VOR);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return stream;
        } else {
            return null;
        }
    }

    private String getLocalPath() {
        if (!TextUtils.isEmpty(data.getsId())) {
            System.out.println("ENC PIC --> " + data.getPath());
            return data.getPath();
        }
        return null;
//        return Constant.PATH_ENC;
    }

    @Override
    public void cleanup() {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                //e.printStackTrace();
            } finally {
                is = null;
            }
        }
    }

    @Override
    public String getId() {
        return data.getsId();
//        return "123";
    }

    @Override
    public void cancel() {
        canceled = true;
    }
}
